package com.android.picotts.ui.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.android.picotts.MyApplication;
import com.android.picotts.R;
import com.android.picotts.businiss.SpriterManager;
import com.android.picotts.businiss.model.Spriter;
import com.android.picotts.businiss.model.SpriterType;
import com.android.picotts.ui.activity.common.TemplateActivity;
import com.android.picotts.ui.activity.pick.PickAppActivity;
import com.android.picotts.ui.activity.pick.PickFileActivity;
import com.android.picotts.ui.activity.pick.PickWebActivity;
import com.android.picotts.ui.widget.FlowLayout;
import com.android.picotts.ui.widget.SpirteView;
import com.android.picotts.ui.widget.TitleBar;
import com.android.picotts.util.Constant;
import com.android.picotts.util.IntentUtils;
import com.android.picotts.util.MessageBus;
import com.android.picotts.util.MessageBus.MMessage;
import com.android.picotts.util.MessageBus.UIReceiver;

/** 主界面 */
public class MainActivity extends  TemplateActivity implements OnClickListener{

    public static final int REQ_FILE = 0x12345601;
    public static final int REQ_CONTACT = 0x12345602;
    public static final int REQ_APP = 0x12345603;
    
    private LayoutInflater inflater;
    private FlowLayout flowView;
    private View input_lay,action_lay, select_lay,btn_del;
    private EditText lableEt, inputEt;
    /** */
    private int sel_mode = -1;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setNoTitle();
        setContentView(R.layout.activity_main);
        inflater = LayoutInflater.from(MyApplication.getContext());
        MessageBus.getBusFactory().register(Constant.MSG_ADD_SPRITE, mRevicer);
        MessageBus.getBusFactory().register(Constant.MSG_DEL_SPRITE, mRevicer);
        initViews();
        loadData();
    }
    
    @Override
    protected void setupTitleBar(TitleBar titleBar) {
        titleBar.setRightVisible(false);
    }
    
    @Override
    protected void onDestroy() {
        MessageBus.getBusFactory().unregister(Constant.MSG_ADD_SPRITE, mRevicer);
        MessageBus.getBusFactory().unregister(Constant.MSG_DEL_SPRITE, mRevicer);
        super.onDestroy();
    }
    
    private void loadData() {
        List<Spriter> list = SpriterManager.getInstance(this).getList();
        for(Spriter one  : list) {
            addSpirteView(one);
        }
    }
    
    public void addSpirteView(Spriter one) {
        flowView.addView(one.getView(inflater, one, false));
    }
    
    public void rmvSpirteView(Spriter one) {
        View child = flowView.findViewWithTag(one.uri);
        if(child != null) {
            flowView.removeView(child);
        }
    }
    
    private void changeEditView() {
        int size = flowView.getChildCount();
        for(int i =0; i < size; i++) {
            SpirteView child = (SpirteView)flowView.getChildAt(i);
            child.setEditable(btn_del.isSelected());
        }
    }
    
    private void initViews() {
        flowView = getViewById(R.id.flowView);
        action_lay = getViewById(R.id.action_lay);
        select_lay = getViewById(R.id.select_lay);
        btn_del = getViewById(R.id.btn_del);
        input_lay = getViewById(R.id.input_lay);
        lableEt = getViewById(R.id.lableEt);
        inputEt = getViewById(R.id.inputEt);
    }
    
    private void showSelectView(boolean visible) {
        select_lay.setVisibility(visible ? View.VISIBLE : View.GONE);
        showActionView(false);
    }
    
    private void showActionView(boolean visible) {
        action_lay.setVisibility(visible ? View.VISIBLE : View.GONE);
        showInputView(false);
    }
    
    private void showInputView(boolean visible) {
        input_lay.setVisibility(visible ? View.VISIBLE : View.GONE);
    }
    
    @Override
    public void onClick(View v) {
        switch(v.getId()) {
        case R.id.btn_add:
            showSelectView(v.isSelected());
            break;
        case R.id.btn_del:
            showSelectView(false);
            changeEditView();
            break;
        case R.id.btn_app:
            showActionView(false);
            pickApp();
            break;
        case R.id.btn_phone:
            sel_mode = 1;
            showActionView(v.isSelected());
            break;      
        case R.id.btn_sms:
            sel_mode = 2;
            showActionView(v.isSelected());
            break;
        case R.id.btn_web:
            sel_mode = 3;
            showActionView(v.isSelected());           
            break;
        case R.id.btn_file:
            showActionView(false);
            pickFile();
            break;
        case R.id.btn_input:
            showInputView(v.isSelected());
            break;
        case R.id.btn_lookfor:
            showInputView(false);
            if(sel_mode != 3) pickContact();
            else pickWeb();
            break;
        case R.id.btn_input_ok:
            makeInput(false);
            break;
        case R.id.btn_input_valid:
            makeInput(true);
            break;
        }
    }
    
    private void makeInput(boolean isValid) {
        String name = lableEt.getText().toString();
        String uri = inputEt.getText().toString();
        if(TextUtils.isEmpty(uri)) {
            showToast("输入不能为空！");
            return;
        }
        Spriter one = null;
        switch(sel_mode) {
        case 1:
            one = new Spriter(SpriterType.PHONE, name, uri);
            break;
        case 2:
            one = new Spriter(SpriterType.SMSTO, name, uri);
            break;
        case 3:
            one = new Spriter(SpriterType.WEB, name, uri);
            break;
        }
        if(isValid) {
            one.onClick(this);
        }else {
            SpriterManager.getInstance(this).add(one);
            showInputView(false);
        }
    }
    
    private void pickApp() {
        PickAppActivity.startActivityForResult(this, REQ_APP);
    }
    
    private void pickFile() {
        PickFileActivity.startActivityForResult(this, REQ_FILE);
    }
    
    private void pickWeb() {
        PickWebActivity.startActivity(this, "http://www.baidu.com");
    }
    
    private void pickContact() {
        Intent it = IntentUtils.pickContact();
        startActivityForResult(it, REQ_CONTACT);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if(resultCode == RESULT_OK && data != null) {
            if(requestCode == REQ_FILE) {
                 File file = new File(Uri.decode(data.getData().toString()));
                 SpriterManager.getInstance(this).add(new Spriter(file));
            }else
            if(requestCode == REQ_APP){
                ArrayList<String> pkgs = data.getStringArrayListExtra(PickAppActivity.KEY_APP);                
                try {
                    if(pkgs != null && pkgs.size() > 0) {
                    PackageManager pm = getPackageManager();
                    for(String pkg : pkgs) {
                        ApplicationInfo appInfo = getPackageManager().getApplicationInfo(pkg, PackageManager.GET_META_DATA);
                        String appName = appInfo.loadLabel(pm).toString();
                        SpriterManager.getInstance(this).add(new Spriter(SpriterType.APP, appName, pkg));
                    }
                    }
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }
            }else 
            if(requestCode == REQ_CONTACT){
                Uri contactUri = data.getData();
                String[] projection = {Phone.NUMBER, Phone.DISPLAY_NAME};
                Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);
                cursor.moveToFirst();
                int column = cursor.getColumnIndex(Phone.NUMBER);
                String number = cursor.getString(column);
                int nameIndex = cursor.getColumnIndex(Phone.DISPLAY_NAME);
                String name = cursor.getString(nameIndex);
                SpriterManager.getInstance(this).add(new Spriter(sel_mode ==1 ? SpriterType.PHONE : SpriterType.SMSTO, name, number));
            }
        }
    }
    
    private UIReceiver mRevicer = new UIReceiver() {
        private static final long serialVersionUID = 3450668281193037488L;

        @Override
        public void onReceive(MMessage message) {
            switch(message.what) {
                case Constant.MSG_ADD_SPRITE:
                {
                    Spriter one = (Spriter)message.obj;
                    addSpirteView(one);
                    break;
                }
                case Constant.MSG_DEL_SPRITE:
                {
                    Spriter one = (Spriter)message.obj;
                    rmvSpirteView(one);
                    break;
                }
            }
        }
    };
      
    public static void startActivity(Context context) {
        Intent it = new Intent(context, MainActivity.class);
        if(!(context instanceof Activity)) {
            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(it);
    }
}